package com.example.demo.controller;


import com.example.demo.entiy.Article;
import com.example.demo.entiy.Categories;
import com.example.demo.entiy.Comment;
import com.example.demo.service.ArticleService;
import com.example.demo.service.CategoriesService;
import com.example.demo.service.CommentService;
import com.example.demo.service.StatisticService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Iterator;
import java.util.List;

@Controller
public class BackController {

    @Autowired
    ArticleService articleService;

    @Autowired
    CommentService commentService;

    @Autowired
    StatisticService statisticService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    CategoriesService categoriesService;


    @GetMapping("/admin")
    public String admin(Model model) {
        //查询出一共多少篇文章
        int allArticleCount = articleService.getAllArticleCount();
        model.addAttribute("allArticleCount", allArticleCount);
        //查询出一共多少篇评论
        int allCommentNum = commentService.getAllCommentNum();
        model.addAttribute("allCommentNum", allCommentNum);
        //根据时间进行排序+显示前五条数据(Article)
        PageHelper.startPage(1, 5);
        List<Article> articleOrderByCreatedDesc = articleService.getArticleOrderByCreatedDesc();
        model.addAttribute("articleOrderByCreatedDesc", articleOrderByCreatedDesc);
        //根据时间进行排序+显示前五条数据(Comment)
        PageHelper.startPage(1, 5);
        List<Comment> commentOrderByCreatedDesc = commentService.getCommentOrderByCreatedDesc();
        model.addAttribute("commentOrderByCreatedDesc", commentOrderByCreatedDesc);
        return "/back/index";
    }


    @GetMapping({"/admin/articleEdit", "/admin/articleEdit/articledId/{articledId}"})
    public String articleEdit(
            Model model,
            @PathVariable(value = "articledId", required = false) Integer articledId
    ) {
        //下拉菜单
        List<Categories> categoriesList = categoriesService.getAllCategoriesList();
        model.addAttribute("categoriesList", categoriesList);
        //articledId有值的情况
        if (articledId != null) {
            Article article = articleService.getArticleByArticleId(articledId);
            model.addAttribute("article", article);
            //使得下拉菜单中的内容进行回显
            Article articleCategories = articleService.getArticleCategoriesByArticleId(articledId);
            model.addAttribute("categoriesId", articleCategories.getNewCategories().getId());
        }
        return "/back/article_edit";
    }

    //发布文章
    @GetMapping("/articleForm")
    public String articleForm(Article article) {
        //新文章
        if (article.getId() == null) {
            int allArticleCount = articleService.getAllArticleCount();
            article.setId((allArticleCount + 1));
            article.setThumbnail("/user/img/rand/1.png");
            try {
                //再添加新的文章 不止修改一张表（t_article） 还要修改 （t_statistic）
                articleService.insertArticleByArticle(article);
                statisticService.insertStatistic(article.getId(), 0, 0);
                //添加categories_article
                categoriesService.insertCategories(article.getId(),article.getCategoriesId());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        } else {
            try {
                articleService.updateArticleByArticleId(article);
                //修改categories_article
                int id = categoriesService.getIdByAidAndCid(article.getId(), article.getOdlCategoriesId());
                categoriesService.updateCategoriesBuId(article.getCategoriesId(), id);
            } catch (Exception e) {
                System.out.println("=========");
                System.out.println(e.getMessage());
                System.out.println("=========");
            }
        }
        return "redirect:/admin/articleList/pageNum/1";
    }

    @GetMapping("/admin/articleList/pageNum/{pageNum}")
    public String articleListPage(
            @PathVariable(value = "pageNum") Integer pageNum,
            Model model
    ) {
        PageHelper.startPage(pageNum, 10);
        List<Article> articleList = articleService.getArticleListAndHits();
        model.addAttribute("articleList", articleList);
        PageInfo pageInfo = new PageInfo(articleList);
        model.addAttribute("pageInfo", pageInfo);
        return "/back/article_list";
    }

    @GetMapping("/removeArticleByArticleId")
    public String removeArticleByArticleId(Integer articleId) {
        //在删除文章的时候要清楚外键的关系（应该先删除评论 然后在删除文章 还有static表）
        //删除redis缓存中的内容
        List<Article> articles = (List<Article>) redisTemplate.opsForValue().get("articles");
        try {
            //有时候在删除文章的过程中可能该文章还未添加评论可能会出现报错
            commentService.deleteCommentByArticleId(articleId);
            //删除redis中的内容
            Iterator<Article> iterator = articles.iterator();
            while (iterator.hasNext()) {
                if (articleId.equals(iterator.next().getId())) {
                    iterator.remove();
                }
            }
            redisTemplate.opsForValue().set("articles", articles);
        } catch (Exception e) {
            System.out.println("===============");
            System.out.println(e.getMessage());
            System.out.println("===============");
        } finally {
            statisticService.deleteStatisticByArticleId(articleId);
            articleService.deleteArticleByArticleId(articleId);
            //删除categories_article
            categoriesService.deleteByArticleId(articleId);
        }
        return "redirect:/admin/articleList/pageNum/1";
    }

    @GetMapping("/testController")
    public String testController() {
        return "client/articleDetails";
    }
}
